package com.gexiaobao.pigeon.app.util;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class DESUtils {

    private static final String SECRET_KEY = "egT3Jl2n";

    /**
     * 生成密钥
     * @throws Exception
     */
    public static byte[] initKey() throws Exception{
        //密钥生成器
        KeyGenerator keyGen = KeyGenerator.getInstance("DES");
        //初始化密钥生成器
        keyGen.init(56);
        //生成密钥
        SecretKey secretKey = keyGen.generateKey();
        return secretKey.getEncoded();
    }

    public static byte[] initKeyNow() throws Exception{
        DESKeySpec dks = new DESKeySpec(SECRET_KEY.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(dks);
        return secretKey.getEncoded();
    }

    /**
     * 解密
     */
    public static String decryptDES(String str) throws Exception{
        return new String(decryptDESIn(BytesToHex.hexStringToByte(str),DESUtils.initKeyNow()));
    }

    public static byte[] decryptDESIn(byte[] data, byte[] key) throws Exception{
        //恢复密钥
        SecretKey secretKey = new SecretKeySpec(key, "DES");
        //Cipher完成解密
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        //初始化cipher
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        //解密
        byte[] plain = cipher.doFinal(data);
        return plain;
    }
}